import { handleResponse, Result } from "../util/handler";
import type { ProductAttribute } from './product';

export type SearchResult = {
  store_id: number;
  store_name: string;
  img_path: string;
  product_id: number;
  unit_price: number;
  product_name: string
}

async function searchGoods({ searchString, pageNum, pageSize }: { searchString: string; pageNum: number; pageSize: number }): Promise<Result<SearchResult[]>> {
  const params = new URLSearchParams({ q: searchString, pageNum: ''+pageNum, pageSize: ''+pageSize });
  return await fetch(`/api/goods/search?${params}`, {
    method: 'get',
    credentials: 'same-origin',
  }).then((resp) => handleResponse<SearchResult[]>(resp));
}

interface ProductInfo {
  productId: number;
  productName: string;
  storeName: string;
  storeId: number;
  info: ProductAttribute[]
}

async function queryGoodsInfo(productId: number): Promise<Result<ProductInfo>> {
  return await fetch(`/api/goods/info/${productId}`, {
    method: 'get',
    credentials: 'same-origin',
  }).then((resp) => handleResponse<ProductInfo>(resp));
}

export type {
  ProductInfo
}

export {
  searchGoods,
  queryGoodsInfo
}
